package com.zhentao.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.OrderItem;
import com.zhentao.pojo.Orders;
import com.zhentao.pojo.Product;
import com.zhentao.service.OrderItemService;
import com.zhentao.service.OrdersService;
import com.zhentao.service.ProductService;
import com.zhentao.vo.QueryParam;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderItemService orderItemService;
    @RequestMapping("/findOrders")
    public Result findOrders(@RequestBody QueryParam queryParam){
        Page<Orders> orders = ordersService.findOrders(queryParam);
        return Result.OK(orders);
    }

    @RequestMapping("/stats")
    public Result orderStats() {
        return ordersService.getOrderStats();
    }

    @RequestMapping("/addOrder")
    public Result addOrder(@RequestBody Orders orders){
        try {
            orders.setCreateTime(new Date());
            orders.setStatus(0);
            orders.setUpdateTime(new Date());
            String orderNo = "ORDER" + System.currentTimeMillis();
            orders.setOrderSn(orderNo);

            double totalAmount = 0;
            if (orders.getItems() == null || orders.getItems().isEmpty()) {
                return Result.ERROR("订单明细不能为空");
            }
            for (OrderItem item : orders.getItems()) {
                Product product = productService.getById(item.getProductId());
                if (product == null) {
                    return Result.ERROR("商品不存在");
                }
                item.setProductName(product.getProductName());
                item.setProductPrice(product.getPrice());
                item.setProductAvatar(product.getAvatar());
                item.setCreateTime(new Date());
                totalAmount += product.getPrice() * item.getProductNum();
            }
            orders.setTotalAmount(totalAmount);

            ordersService.save(orders);
            for (OrderItem item : orders.getItems()) {
                item.setOrderId(orders.getOrderId());
                orderItemService.save(item);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("orderNo", orderNo);
            result.put("amount", totalAmount);
            return Result.OK(result);
        } catch (Exception e) {
            e.printStackTrace(); // 控制台输出异常
            return Result.ERROR("下单失败：" + e.getMessage());
        }
    }
}
